package com.atguigu.day03.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink01_TransForm_Map {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        //2.从端口读取字符串数据
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

//        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");
        DataStreamSource<String> streamSource = env.fromElements("s1,1,1");

        //3.TODO 使用map将读过来的字符串转为javaBean
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MyRichMap());

        map.print();

        env.execute();

    }

    //自定义一个类继承富函数
    public static class MyRichMap extends RichMapFunction<String, WaterSensor> {

        /**
         * 声明周期方法
         * open方法在程序最开始时调用，每个并行实例调用一次（指的是每个并行度调用一次）
         * 根据这个特性可以在open方法中初始化一些东西（比如：创建连接）
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open...");
        }

        /**
         * 声明周期方法
         * close方法在程序结束时调用，每个并行实例调用一次（指的是每个并行度调用一次）
         * 在读文件时close方法每个并行实例调用两次
         *
         * 可以写关闭资源相关的代码
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close....");

        }

        @Override
        public WaterSensor map(String value) throws Exception {
            System.out.println(getRuntimeContext().getTaskNameWithSubtasks());
            String[] split = value.split(",");
            return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
        }
    }
}
